package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

public class GkzhanNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={
		
		"http://www.gkzhan.com/news.*/detail/[0-9]*.html",
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("div.newshow_title").text();	
		if(StringUtils.isBlank(title)){
			title =doc.select("div.newstitle").text();	
		}
		if(StringUtils.isBlank(title))
			title =doc.select("h1").text();
		content=HtmlCleaner.getContentHtml(url,doc.select("div.newshow_fontshow"));
		if(StringUtils.isBlank(content))
			content=HtmlCleaner.getContentHtml(url,doc.select("div.newsContent"));
		String text=doc.select("div.newstime").text();
		date=DateUtils.matchDate(text);
		author=JSoupUtils.matchAuthor(doc, "来源：");
		if(author==null){
			author=StringUtils.substringBetween(text, "信息来源： ", "   ");
		}
		if(author!=null && author.endsWith("工控中国")){
			author=null;
		}
		if (StringUtils.isBlank(title) ||date==null){
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setDate(date);	
		news.setAuthor(author);
		return news;
	}	
	
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
	
	public static void main(String[] args) {
		String url="http://www.gkzhan.com/News/Detail/41862.html";
		GkzhanNewsAnalyse analyse=new GkzhanNewsAnalyse();		
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

}
